<template>
  <div class="svg-interceptor-popup">
    <!-- 状态显示区域 -->
    <div class="status-section">
      <div class="status-indicator">
        <div class="status-dot" :style="{ background: statusDotColor }"></div>
        <span class="status-text">{{ statusText }}</span>
      </div>
      <div class="site-status" :style="{ color: siteStatusColor }">
        {{ siteStatus }}
      </div>
    </div>

    <!-- 控制按钮 -->
    <div class="controls-section">
      <button :class="toggleBtnClass" @click="toggleInterception" class="control-btn">
        <span class="btn-icon">{{ toggleIcon }}</span>
        <span>{{ toggleText }}</span>
      </button>

      <button class="control-btn btn-secondary" @click="clearSvgData">
        <span class="btn-icon">🗑️</span>
        <span>清除记录</span>
      </button>
    </div>

    <!-- 通知组件 -->
    <div
      v-if="notification.show"
      :class="`notification ${notification.type}`"
      class="notification-popup"
    >
      {{ notification.message }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import browser from 'webextension-polyfill'

// 响应式状态
const isIntercepting = ref(true)
const svgList = ref<any[]>([])

// 状态显示相关
const statusText = ref('未在蓝湖网站')
const siteStatus = ref('非蓝湖网站')
const isLanhuSite = ref<boolean>(false)

// 计数器动画状态
const counterTransform = ref('scale(1)')
const counterColor = ref('#007bff')

// 通知状态
const notification = reactive({
  show: false,
  message: '',
  type: 'success',
})

const statusDotColor = computed(() => {
  if (!isLanhuSite.value) return '#6c757d'
  return isIntercepting.value ? '#28a745' : '#ffc107'
})

const siteStatusColor = computed(() => {
  return isLanhuSite.value ? '#28a745' : '#6c757d'
})

const toggleText = computed(() => {
  return isIntercepting.value ? '暂停拦截' : '开始拦截'
})

const toggleIcon = computed(() => {
  return isIntercepting.value ? '⏸️' : '▶️'
})

const toggleBtnClass = computed(() => {
  return isIntercepting.value ? 'btn-primary' : 'btn-warning'
})

// 方法实现
const checkIntercepting = async () => {
  try {
    const result = await browser.storage.local.get('intercepting')
    isIntercepting.value = (result.intercepting || false) as boolean
  } catch (error) {
    console.error('检查拦截状态失败:', error)
  }
}

const checkCurrentSite = async () => {
  try {
    const [tab] = await browser.tabs.query({
      active: true,
      currentWindow: true,
    })
    if (!tab) return

    const isLanhu = tab.url && (tab.url.includes('lanhuapp.com') || tab.url.includes('lanhu.com'))
    isLanhuSite.value = !!isLanhu

    await checkIntercepting()
    updateSiteStatus()
  } catch (error) {
    console.error('检查当前网站失败:', error)
    isLanhuSite.value = false
    updateSiteStatus()
  }
}

const updateSiteStatus = () => {
  if (isLanhuSite.value) {
    statusText.value = isIntercepting.value ? '正在拦截' : '已暂停'
    siteStatus.value = '蓝湖网站'
  } else {
    statusText.value = '未在蓝湖网站'
    siteStatus.value = '非蓝湖网站'
  }
}

const toggleInterception = async () => {
  isIntercepting.value = !isIntercepting.value

  try {
    await browser.runtime.sendMessage({
      action: 'toggleInterception',
      data: isIntercepting.value,
    })

    await browser.storage.local.set({ intercepting: isIntercepting.value })

    updateSiteStatus()

    showNotification(isIntercepting.value ? '已开启SVG拦截' : '已暂停SVG拦截')
  } catch (error) {
    console.error('切换拦截状态失败:', error)
    showNotification('操作失败', 'error')
  }
}

const clearSvgData = async () => {
  if (!confirm('确定要清除所有SVG记录吗？此操作无法撤销。')) {
    return
  }

  try {
    await browser.runtime.sendMessage({ action: 'clearSvgData' })

    svgList.value = []
    showNotification('SVG记录已清除')
  } catch (error) {
    console.error('清除SVG数据失败:', error)
    showNotification('清除失败', 'error')
  }
}

const animateCounter = () => {
  counterTransform.value = 'scale(1.2)'
  counterColor.value = '#28a745'

  setTimeout(() => {
    counterTransform.value = 'scale(1)'
    counterColor.value = '#007bff'
  }, 300)
}

const showNotification = (message: string, type: string = 'success') => {
  notification.message = message
  notification.type = type
  notification.show = true

  setTimeout(() => {
    notification.show = false
  }, 2000)
}

// 工具函数
const extractFileName = (url: string) => {
  try {
    const urlObj = new URL(url)
    const pathname = urlObj.pathname
    const fileName = pathname.split('/').pop()

    if (fileName && fileName.includes('.')) {
      return fileName
    }

    return `svg_${Date.now()}.svg`
  } catch {
    return `svg_${Date.now()}.svg`
  }
}

// 消息监听器
const setupMessageListener = () => {
  browser.runtime.onMessage.addListener((message: any) => {
    if (message.action === 'svgCaptured') {
      console.log('收到SVG捕获通知:', message.data)

      const fileName = extractFileName(message.data.at(-1).url)
      showNotification(`✅ 已拦截: ${fileName}`, 'success')

      svgList.value = message.data
      animateCounter()
    }
  })
}

// 生命周期
onMounted(async () => {
  browser.storage.local.set({ intercepting: isIntercepting.value })
  await checkCurrentSite()
  setupMessageListener()
})
</script>

<style scoped>
.svg-interceptor-popup {
  width: 350px;
  padding: 16px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  background: #fff;
}

.status-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  transition: background 0.3s ease;
}

.status-text {
  font-weight: 500;
  font-size: 14px;
}

.site-status {
  font-size: 12px;
  font-weight: 500;
}

.counter-section {
  margin-bottom: 16px;
  text-align: center;
}

.svg-counter {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.counter-label {
  font-size: 14px;
  color: #6c757d;
}

.counter-value {
  font-size: 24px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.controls-section {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.control-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 10px 12px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover {
  background: #0056b3;
}

.btn-warning {
  background: #ffc107;
  color: #212529;
}

.btn-warning:hover {
  background: #e0a800;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #545b62;
}

.svg-list-section h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #333;
}

.svg-list {
  max-height: 200px;
  overflow-y: auto;
}

.svg-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 8px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.svg-info {
  flex: 1;
}

.svg-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.svg-meta {
  display: flex;
  gap: 12px;
}

.svg-size,
.svg-time {
  font-size: 12px;
  color: #6c757d;
}

.svg-actions {
  display: flex;
  gap: 4px;
}

.btn-icon-small {
  width: 28px;
  height: 28px;
  border: none;
  background: #fff;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background 0.2s ease;
}

.btn-icon-small:hover {
  background: #e9ecef;
}

.empty-state {
  text-align: center;
  padding: 32px 16px;
  color: #6c757d;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.empty-text {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
}

.empty-hint {
  font-size: 14px;
}

.notification-popup {
  position: fixed;
  top: 10px;
  right: 10px;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  z-index: 1000;
  animation: slideIn 0.3s ease;
}

.notification.success {
  background: #28a745;
  color: white;
}

.notification.error {
  background: #dc3545;
  color: white;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}
</style>
